<template>
  <div>
    <el-dialog :modal-append-to-body='false' v-dialogDrag width="680px" title="查看图片" v-loading='loading'
               @close='dialogImgPathClose' :visible.sync="dialogImgPath" :close-on-click-modal="false" append-to-body>
      <div style="width:100%;height:400px;overflow-y:auto">
        <el-button size='small' @click="photoUpByPhone" type="primary">手机上传</el-button>
        <el-button size='small' @click="photoRefresh" type="primary">刷新</el-button>
        <el-dialog :modal-append-to-body='false' v-dialogDrag width="280px" title="微信扫一扫上传" @close='dialogPhoneClose'
                   :visible.sync="dialogPhone" :close-on-click-modal="false" append-to-body>
          <el-row type="flex" class="row-bg" justify="space-around">
            <el-col :span="24" align='center'>
              <!-- <canvas id="QRCode"></canvas> -->
              <vue-qr :text="phoneUrl" :margin='0' colorDark="#333" colorLight="#fff" :size="200"></vue-qr>
            </el-col>
          </el-row>
        </el-dialog>
        <!-- <span>{{'图片'+imgNum+'张'+' '+'文件'+fileNum+'个'}}</span> -->
        <!--name="file" 默认为file :data为额外字段 -->
        <el-upload
          class="uploadPhoto"
          :action=uploadUrl
          :data="picData"
          :file-list="fileList"
          :before-remove='beforeRemove'
          :before-upload="beforeUpload"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemove"
          :on-preview="downloadText"
          multiple
        >
        </el-upload>
        <el-upload
          class="uploadText"
          :action=uploadUrl
          :data="picData"
          :file-list="photoList"
          list-type="picture-card"
          :before-remove='beforeRemove'
          :before-upload="beforeUpload"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemove"
          :on-preview="seeBigPhotos"
          multiple
        >
          <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
        </el-upload>
        <el-dialog :modal-append-to-body='false' v-dialogDrag :visible.sync="dialogBigImg" append-to-body>
          <img width="100%" :src="bigImgUrl"/>
        </el-dialog>
      </div>
      <div slot="footer" v-show='needSavePhoto'>
        <el-button @click="dialogImgPath=false">取消</el-button>
        <el-button @click='savePhotos' type="primary">保存</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import vueQr from 'vue-qr'
import {
  addPhoto,
  changePhotoFailure,
  delPhoto,
  getMobUploadUrl,
  getPhotoByRandom,
  getPhotoByTableId,
  getPhotoToken,
  recoveryPhoto
} from "@/api/info/photo";

/**
 * 父传子，大小写不敏感故不是驼峰命名,
 * 依次绑定为弹窗,
 * 保存按钮,
 * 上传图片外表id ,
 * 随机数,
 * 上传图片外表类型 ,
 * 上传图片类型（公有||私有）
 * 传参可优化，dialog不必要
 * 接收可优化，watch不必要，
 */
export default {
  props: ['dialog', 'save', 'photoid', 'random', 'type', 'bucket'],
  components: {
    vueQr
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_UPLOAD_API + "/common/upload",
      textUrl: require('../../assets/images/text.jpg'),
      loading: false,
      dialogBigImg: false,//查看大图弹框
      dialogImgPath: false,//查看图片弹框
      dialogPhone: false,//手机上传弹框
      delIdStr: '',//删除图片id集合
      delInfoStr: '',//删除图片名称集合
      bigImgUrl: '',//大图url路径
      fileNum: 0,//文件数量
      imgNum: 0,//图片数量
      fileList: [],//文件数组
      photoList: [],//所有图片显示数组
      phoneUrl: '',//手机上传二维码
      picData: {//上传图片前的格式
        token: "",
        "x:random": '', //十二位随机数
        "x:tableType": '', //审批，任务
        "x:mimeType": "", //文件，图片
        "x:bucket": "" //公有，私有
      },
      photoBucket: '私有', //默认私有
      tableId: '',//外表id保存的时候传
      needSavePhoto: false,//false代表不需要保存图片
      imgDelId: [],//删除图片id集合
    }
  },

  watch: {
    dialog(val) {
      console.log(val)
      this.dialogImgPath = val
    },
    save(val) {
      console.log(val)
      this.needSavePhoto = val
    },
    photoid(val) {
      console.log(val)
      this.tableId = val
    },
    random(val) {
      console.log(val)
      this.picData["x:random"] = val
    },
    type(val) {
      console.log(val)
      this.picData["x:tableType"] = val
    },
    bucket(val) {
      this.photoBucket = val ? '公有' : '私有'
      console.log(val, 1, this.photoBucket)
    }
  },
  created() {
    this.dialogImgPath = this.dialog
    this.needSavePhoto = this.save
    this.tableId = this.photoid
    this.picData["x:random"] = this.random
    this.picData["x:tableType"] = this.type
    this.photoBucket = this.photoBucket ? '公有' : '私有'
    this.photoRefresh()
  },
  methods: {
    getToken() {//获取token
      return getPhotoToken(this.photoBucket).then(({result: res}) => {
        return res
      });
    },
    async beforeUpload(file) {//上传前
      console.log(file)
      try {
        let getToken = await this.getToken();//上传前先获取token
        this.picData.token = getToken;
        if (file.type == "image/jpeg" || file.type == "image/jpg" || file.type === "image/gif" || file.type == "image/png" || file.type == "image/bmp") {
          this.picData["x:mimeType"] = "图片"
        } else {
          this.picData["x:mimeType"] = "文件"
        }
        this.picData["x:filename"] = file.name;
        this.picData["x:bucket"] = this.photoBucket;
      } catch (err) {
        console.log(err);
      }
    },
    handleAvatarSuccess(res, file, fileList) {//上传成功后
      if(res && res.status != 200){
        this.$message.error(res.msg)
        return
      }
      file.url = res.result
      // this.photoRefresh()
      this.photoList = fileList
      console.log(res, file, fileList)
    },
    seeBigPhotos(file) {//查看大图
      this.bigImgUrl = file.url;
      this.dialogBigImg = true;
    },
    downloadText(file) {//下载文件
      window.open(file.url)
    },
    beforeRemove(file, fileList) {//删除前
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove(file, fileList) {//删除后（走接口真删除）
      console.log(1, file)
      if (this.needSavePhoto) {
        this.imgDelId.push(file.response.result);
        changePhotoFailure(file.response.result).then(res => {
        });
      } else {
        delPhoto(file.response.result).then(res => {
          this.$message.success('删除成功')
        })
      }
    },

    deletePhotos(id) {//删除图片
      delPhoto(id.join(',')).then(res => {
        this.dialogImgPath = false
        this.$message.success('保存成功')
        this.imgDelId = []
      })
    },
    recoverImg() {//恢复图片
      if (!this.tableId) {
        return
      }
      recoveryPhoto(this.tableId, this.picData["x:tableType"])
    },
    photoUpByPhone() {//手机上传
      this.dialogPhone = true
      let params = {
        bucket: this.photoBucket,
        mimeType: '图片',
        random: this.picData["x:random"],
        tableType: this.picData["x:tableType"],
      }
      getMobUploadUrl(params).then(({result: res}) => {
        this.phoneUrl = res
      })
    },
    async photoRefresh() {//查询已有照片和临时照片&&刷新按钮
      this.imgNum = 0
      this.fileNum = 0
      this.photoList = []
      this.fileList = []
      // this.loading=true
      if (this.tableId) {//true表示要查已有的图片
        await this.getPhotoByTableId()
      }
      //通过随机数查临时图片
      await getPhotoByRandom(this.picData["x:random"], this.picData["x:tableType"], '临时').then(({result: res}) => {
        this.loading = false
        if (res.length == 0) {
          return
        }
        for (let i = 0; i < res.length; i++) {//将图片拼接为element识别格式
          let obj = {
            status: res[i].status,
            mimeType: res[i].mimeType,
            name: res[i].name,
            url: res[i].url,
            response: {
              result: res[i].photoId
            }
          };
          if (res[i].mimeType == '图片') {
            this.photoList.push(obj);
          } else if (res[i].mimeType == '文件') {
            this.fileList.push(obj);
          }
        }
      }).catch(err => {
        this.loading = false
      })

    },
    async getPhotoByTableId() {//通过外表id查已有图片
      await getPhotoByTableId(this.tableId, this.picData["x:tableType"], '正常').then(({result: res}) => {
        if (res.length == 0) {
          return
        }
        for (let i = 0; i < res.length; i++) {//将图片拼接为element识别格式
          let obj = {
            status: res[i].status,
            mimeType: res[i].mimeType,
            name: res[i].name,
            url: res[i].url,
            response: {
              result: res[i].photoId
            }
          };
          if (res[i].mimeType == '图片') {
            this.photoList.push(obj);
          } else if (res[i].mimeType == '文件') {
            this.fileList.push(obj);
          }
        }
        console.log(this.photoList, 2)
      })
    },
    dialogPhoneClose() {//手机上传弹窗关闭
      this.photoRefresh()
    },
    savePhotos() {//保存按钮，所有新上传的图片有保存按钮不点保存都不会真上传，无保存按钮的传随机数给后台保存
      let flag = this.photoList.some(item => {//判断有无新增照片
        console.log(item, 2)
        return item.status != '正常'
      })
      let flag2 = this.fileList.some(item => {//判断有无新增照片
        console.log(item, 2)
        return item.status != '正常'
      })
      console.log(flag, 3)
      if ((!flag || this.photoList.length == 0) && (!flag2 || this.fileList.length == 0) && this.imgDelId.length == 0) {
        this.$message.warning('没有新增照片，无需保存')
        return
      }
      if (this.imgDelId.length > 0) {//判断有无删除图片
        this.deletePhotos(this.imgDelId)
      }
      if ((!flag || this.photoList.length == 0) && (!flag2 || this.fileList.length == 0)) {
        return
      }
      this.loading = true
      let data = {
        random: this.picData["x:random"],
        tableId: this.tableId,
        tableType: this.picData["x:tableType"]
      }
      addPhoto(data).then(res => {
        this.loading = false
        this.dialogImgPath = false
        this.$message.success('保存成功')
      }).catch(err => {
        this.loading = false
      })

    },
    dialogImgPathClose() {
      if (this.tableId) {
        this.recoverImg()
        this.imgDelId = []
        this.photoList = []
      }
      this.$emit('listenEvent', false)
    },
  }
}
</script>

<style lang="scss">
.el-upload-list__item {
  transition: none !important;
}

.uploadPhoto {

  .el-upload--picture-card {
    display: none;
  }
}

.uploadText {
  .el-upload--picture-card {
    border: none;
    line-height: 0;
    width: 0;
    height: 0;
    background-color: #fff;
  }

  .el-upload {
    position: absolute;
    top: 84px;
    left: 178px;
  }
}

</style>
